import { Modal, Upload, Button, message } from "antd";
import Cropper, { ReactCropperElement } from "react-cropper";
import { useState, useRef, useEffect } from "react";
import "cropperjs/dist/cropper.css";
import { UploadOutlined } from "@ant-design/icons";
interface ImageClipProps {
    visible: boolean;
    cropBox?: { width: number; height: number };
    onOk: (blob: Blob, fileName: string) => void;
    onCancel: () => void;
}
const ImageClip = (props: ImageClipProps) => {
    const cropperRef = useRef<ReactCropperElement>(null);
    const [file, setFile] = useState({ URL: null, fileName: "" });
    const fileProps = {
        showUploadList: false,
        beforeUpload(file: File) {
            if (file.type !== "image/png" && file.type !== "image/jpeg") {
                message.error(`${file.name} is not a png,jpg file`);
            }
            return file.type === "image/png" || file.type === "image/jpeg"
                ? true
                : Upload.LIST_IGNORE;
        },
        customRequest(data: any) {
            console.log(data);
            const fileReader = new FileReader();
            fileReader.onload = (e: any) => {
                const dataURL = e.target.result;
                setFile({ URL: dataURL, fileName: data.file.name });
            };
            fileReader.readAsDataURL(data.file);
        },
    };
    useEffect(() => {
        setTimeout(() => {
            cropperRef.current?.cropper.setCropBoxData(
                props.cropBox ?? { width: 50, height: 50 }
            );
        }, 200);
    }, [file]);
    return (
        <Modal
            visible={props.visible}
            title="图片裁剪"
            onCancel={props.onCancel}
            onOk={() => {
                cropperRef.current?.cropper.getCroppedCanvas().toBlob(blob => {
                    props.onOk(blob!, file.fileName);
                });
            }}
        >
            <div style={{ marginBottom: 10 }}>
                <Upload {...fileProps}>
                    <Button icon={<UploadOutlined />}>选择文件</Button>
                </Upload>
            </div>
            <Cropper
                src={file.URL!}
                className="company-logo-cropper"
                style={{ height: 400, width: "100%" }}
                ref={cropperRef}
                // Cropper.js options
                viewMode={1}
                aspectRatio={1} // 这个是设置比例的参数 我这里设置的1:1
                guides={false}
                cropBoxResizable={false}
                dragMode="move"
                toggleDragModeOnDblclick={false}
            />
        </Modal>
    );
};
export default ImageClip;
